//
//  BRMapView.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/2.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRMapView.h"
#import "BRMarkerView.h"
//集群相关
#import "GMUNonHierarchicalDistanceBasedAlgorithm.h"
#import "GMUClusterManager.h"
#import "GMUDefaultClusterIconGenerator.h"
#import "GMUDefaultClusterRenderer.h"
#import "GMUClusterRenderer.h"
#import "POIItem.h"

#import "BRStationListModel.h"

#define kGoogleZoom  16.0

@interface BRMapView ()<GMSMapViewDelegate,CLLocationManagerDelegate,GMUClusterRendererDelegate>
{
    GMUClusterManager *_clusterManager;
    
    UIView *_shadowViw;
}

@property (nonatomic,strong) GMSMarker *myM;
@property (nonatomic,strong) UIView *nearbySearchCenterView;  // 附近网点中心标记视图（悬浮在地图上层，永远居中）
@property (nonatomic,strong) UIButton *zoomInButton;   // 放大按钮
@property (nonatomic,strong) UIButton *zoomOutButton;  // 缩小按钮

@end

@implementation BRMapView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColor.qd_backgroundColor2;
        // 从全局位置管理器获取位置，如果没有则使用(0,0)，等待真实定位
        CLLocationCoordinate2D globalLocation;
        if ([BRTools respondsToSelector:@selector(br_getGlobalLocation)]) {
            globalLocation = [BRTools br_getGlobalLocation];
        } else {
            // 如果方法不存在，使用(0,0)，等待真实定位
            globalLocation = CLLocationCoordinate2DMake(0, 0);
        }
        self.myLocation = globalLocation;
        self.centLocation = globalLocation;
        self.nearbySearchLocation = globalLocation;  // 默认和当前位置重合
        [self setUI];
    }
    return self;
}

- (void)startUpdatingLocation {
    
    dispatch_queue_t  queue = dispatch_queue_create(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
    dispatch_async(queue, ^{
        if ([CLLocationManager locationServicesEnabled]) {
            //启动跟踪定位
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.locationManager startUpdatingLocation];
            });
        }
    });
}

- (void)stopUpdateLocation {
    [self.locationManager stopUpdatingLocation];
}


- (void)requestLocation {
    [self.locationManager requestLocation];
}

- (void)forceUpdateLocation {
    // 强制更新定位到当前位置
    [self.locationManager stopUpdatingLocation];
    [self.locationManager startUpdatingLocation];
}

- (void)setGMSMarkerShop {
    // 确保所有地图操作都在主线程执行
    if ([NSThread isMainThread]) {
        [self.mapView clear];
        [_clusterManager clearItems];
        
        POIItem <GMUClusterItem> *item =
        [[POIItem alloc] initWithPosition:CLLocationCoordinate2DMake(self.myLocation.latitude, self.myLocation.longitude) name:@"station"];
        item.icon = BRImage(@"home_shop");
        
        [_clusterManager addItem:item];
        
        [_clusterManager cluster];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setGMSMarkerShop];
        });
    }
}

- (void)createMyLocationLogo {
    POIItem <GMUClusterItem> *item =
    [[POIItem alloc] initWithPosition:CLLocationCoordinate2DMake(self.myLocation.latitude, self.myLocation.longitude) name:@"station"];
    item.icon = BRImage(@"home_shop");
    
    [_clusterManager addItem:item];
}

- (void)setGMSMarkerShop:(NSArray *)businessArr
{
    // 确保所有地图操作都在主线程执行
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setGMSMarkerShop:businessArr];
        });
        return;
    }
    
    [self.mapView clear];
    [_clusterManager clearItems];
    
    // 清除后重新初始化标记
    self.myM = nil;
    
    NSMutableArray *itemsA = [NSMutableArray array];
    
    for (int i = 0;i < businessArr.count;i++) {
        BRStationListModel *model = businessArr[i];
        UIImage *image;
        // 使用新接口的 open 字段（兼容旧接口的 isBusiness）
        BOOL isOpen = model.open;  // 新接口使用 open 字段
        if (isOpen) {
            image = model.isTap ? UIImage.qd_homeLocBigImg : UIImage.qd_homeLocImg ;
        }else {
            image =  model.isTap ? UIImage.qd_homeLocCloseBigImg  : UIImage.qd_homeLocCloseImg ;
        }

        // 根据H5代码，后端返回的是BD09坐标，需要转换为GCJ02显示到Google Maps
        // H5代码：var point = coordtransform.bd09togcj02(info.lng, info.lat);
        CLLocationCoordinate2D gcj02Position = [BRTools br_bd09ToGcj02:model.lat lng:model.lng];
        
        POIItem <GMUClusterItem> *item =
        [[POIItem alloc] initWithPosition:gcj02Position name:@"商家"];
        item.icon = image;
        item.isTap = model.isTap;
        item.index = i;
        [itemsA addObject:item];
//        NSLog(@"lat = [%f],lng = [%f]",item.position.latitude,item.position.longitude);
    }
    NSLog(@"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    NSLog(@"📍 刷新网点");
    NSLog(@"中心点位坐标: (%.8f, %.8f)", self.nearbySearchLocation.latitude, self.nearbySearchLocation.longitude);
    NSLog(@"当前位置坐标: (%.8f, %.8f)", self.myLocation.latitude, self.myLocation.longitude);
    NSLog(@"地图中心坐标: (%.8f, %.8f)", self.centLocation.latitude, self.centLocation.longitude);
    NSLog(@"网点数量: %lu", (unsigned long)itemsA.count);
    NSLog(@"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    
    [_clusterManager addItems:itemsA];
    [_clusterManager cluster];
    
    // 重新显示当前位置标记（因为 clear 会清除所有标记）
    [self showMyLocationMarker];
    // 附近网点中心视图不需要重新创建，因为它始终悬浮在地图上层
}

/// 显示当前位置的点位标记
- (void)showMyLocationMarker {
    // 确保所有地图操作都在主线程执行
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showMyLocationMarker];
        });
        return;
    }
    
    // 移除旧的当前位置标记
    if (self.myM) {
        self.myM.map = nil;
        self.myM = nil;
    }
    
    // 创建蓝色定位图标
    UIView *markerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
    markerView.backgroundColor = UIColor.clearColor;
    
    // 外圈（蓝色圆环）
    UIView *outerCircle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
    outerCircle.backgroundColor = UIColorMakeWithRGBA(0, 122, 255, 0.3);  // 半透明蓝色
    outerCircle.layer.cornerRadius = 12;
    outerCircle.layer.masksToBounds = YES;
    [markerView addSubview:outerCircle];
    
    // 内圈（蓝色实心圆）
    UIView *innerCircle = [[UIView alloc] initWithFrame:CGRectMake(6, 6, 12, 12)];
    innerCircle.backgroundColor = UIColorMakeWithRGBA(0, 122, 255, 1);  // 蓝色
    innerCircle.layer.cornerRadius = 6;
    innerCircle.layer.masksToBounds = YES;
    [markerView addSubview:innerCircle];
    
    // 中心点（白色小点）
    UIView *centerDot = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 4, 4)];
    centerDot.backgroundColor = UIColor.whiteColor;
    centerDot.layer.cornerRadius = 2;
    centerDot.layer.masksToBounds = YES;
    [markerView addSubview:centerDot];
    
    // 将视图转换为图片
    UIGraphicsBeginImageContextWithOptions(markerView.bounds.size, NO, [UIScreen mainScreen].scale);
    [markerView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *markerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // 创建当前位置标记
    self.myM = [[GMSMarker alloc] init];
    self.myM.position = self.myLocation;
    self.myM.icon = markerImage;  // 使用蓝色定位图标
    self.myM.groundAnchor = CGPointMake(0.5, 0.5);  // 设置锚点为中心点
    self.myM.map = self.mapView;
    self.myM.zIndex = 1000;  // 确保当前位置标记在最上层
    NSLog(@"📍 显示当前位置标记: (%.6f, %.6f)", self.myLocation.latitude, self.myLocation.longitude);
}

/// 显示附近网点中心标记视图（悬浮在地图上层，永远居中）
- (void)showNearbySearchMarker {
    // 如果视图已存在，直接返回
    if (self.nearbySearchCenterView && self.nearbySearchCenterView.superview) {
        return;
    }
    
    // 创建包含图标和文字的容器视图
    UIView *markerContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
    markerContainer.backgroundColor = UIColor.clearColor;
    markerContainer.userInteractionEnabled = NO;  // 不拦截触摸事件，让地图可以正常操作
    
    // 文字标签（白色圆角矩形气泡）
    UIView *labelBg = [[UIView alloc] initWithFrame:CGRectMake(5, 0, 70, 24)];
    labelBg.backgroundColor = UIColor.whiteColor;
    labelBg.layer.cornerRadius = 12;
    labelBg.layer.masksToBounds = YES;
    // 添加轻微阴影
    labelBg.layer.shadowColor = UIColor.blackColor.CGColor;
    labelBg.layer.shadowOffset = CGSizeMake(0, 1);
    labelBg.layer.shadowOpacity = 0.1;
    labelBg.layer.shadowRadius = 2;
    [markerContainer addSubview:labelBg];
    
    QMUILabel *label = [[QMUILabel alloc] initWithFrame:CGRectMake(0, 0, 70, 24)];
    label.text = Localized(@"home_nearbyStations");
    label.textColor = UIColorMakeWithHex(@"#333333");
    label.font = [UIFont fontM:12];
    label.textAlignment = NSTextAlignmentCenter;
    [labelBg addSubview:label];
    
    // 圆环视图（作为中心标记）
    UIView *circleView = [[UIView alloc] initWithFrame:CGRectMake(30, 28, 20, 20)];
    circleView.backgroundColor = UIColor.clearColor;
    
    // 外圆环（深灰色）
    CAShapeLayer *outerCircleLayer = [CAShapeLayer layer];
    UIBezierPath *outerCirclePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(10, 10)
                                                                     radius:9
                                                                 startAngle:0
                                                                   endAngle:M_PI * 2
                                                                  clockwise:YES];
    outerCircleLayer.path = outerCirclePath.CGPath;
    outerCircleLayer.fillColor = UIColor.clearColor.CGColor;
    outerCircleLayer.strokeColor = UIColorMakeWithHex(@"#666666").CGColor;  // 深灰色
    outerCircleLayer.lineWidth = 2.0;
    [circleView.layer addSublayer:outerCircleLayer];
    
    // 中心点（深灰色实心圆）
    UIView *centerDot = [[UIView alloc] initWithFrame:CGRectMake(7, 7, 6, 6)];
    centerDot.backgroundColor = UIColorMakeWithHex(@"#666666");  // 深灰色
    centerDot.layer.cornerRadius = 3;
    centerDot.layer.masksToBounds = YES;
    [circleView addSubview:centerDot];
    
    [markerContainer addSubview:circleView];
    
    // 保存为属性
    self.nearbySearchCenterView = markerContainer;
    
    // 添加到地图视图的上层（不是地图内部，而是BRMapView上）
    // 确保它在地图视图之后添加，这样它就会在地图的上层
    [self insertSubview:self.nearbySearchCenterView aboveSubview:self.mapView];
    
    // 使用约束让视图始终居中
    [self.nearbySearchCenterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.centerY.equalTo(self);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(50);
    }];
    
    NSLog(@"📍 显示附近网点中心标记视图（悬浮在地图上层，永远居中）");
}

- (void)resetMapStyle {
    
    NSError *error = nil;
    self.mapView.mapStyle = [GMSMapStyle styleWithJSONString:[BRThemeManage br_mapStylePatchWithJsonFile] error:&error];
    if (!error) {
        NSLog(@"mapStyle Err = %@",error);
    }
}

- (void)br_animateToCameraPosition:(CLLocationCoordinate2D)Coordinate {
    
    GMSCameraPosition *camera =  [GMSCameraPosition cameraWithLatitude:Coordinate.latitude longitude:Coordinate.longitude zoom:kGoogleZoom];
    
    [self.mapView animateToCameraPosition:camera];
}


#pragma mark - Google Delegate && Location Manager--
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *curLocation = [locations firstObject];
    CLLocationCoordinate2D curCoordinate2D = curLocation.coordinate;
    
    // 检查获取到的位置是否有效（基本的坐标范围检查）
    BOOL isValidLocation = (curCoordinate2D.latitude != 0 && curCoordinate2D.longitude != 0 && 
                           curCoordinate2D.latitude >= -90 && curCoordinate2D.latitude <= 90 &&
                           curCoordinate2D.longitude >= -180 && curCoordinate2D.longitude <= 180);
    
    // 只有位置有效时才更新，使用真实设备位置
    if (isValidLocation) {
        self.myLocation = curCoordinate2D;
        self.centLocation = curCoordinate2D;
        
        // 同步更新全局位置管理器
        USERManager.globalLatitude = curCoordinate2D.latitude;
        USERManager.globalLongitude = curCoordinate2D.longitude;
        
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:curCoordinate2D.latitude longitude:curCoordinate2D.longitude zoom:kGoogleZoom];
        
        if (self.mapView.isHidden) {
            self.mapView.hidden = NO;
            self.mapView.camera = camera;
        } else {
            [self.mapView animateToCameraPosition:camera];
        }
        
        // 显示当前位置标记
        [self showMyLocationMarker];
        // 更新附近网点位置为当前位置
        self.nearbySearchLocation = curCoordinate2D;
        // 显示附近网点中心标记视图
        [self showNearbySearchMarker];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(br_locationManager:didUpdateLocations:)]) {
            [self.delegate br_locationManager:manager didUpdateLocations:locations];
        }
    }
    
    // 停止定位服务，避免持续定位
    [self stopUpdateLocation];
}

// Handle location manager errors.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    [manager stopUpdatingLocation];
    
    // 定位失败时，如果有全局位置则使用，否则保持当前状态
    if (!self.mapView || self.mapView.isHidden) {
        self.mapView.hidden = NO;
        // 尝试从全局位置管理器获取位置
        CLLocationCoordinate2D globalLocation = [BRTools br_getGlobalLocation];
        if (globalLocation.latitude != 0 && globalLocation.longitude != 0) {
            GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:globalLocation.latitude
                                                                     longitude:globalLocation.longitude
                                                                          zoom:kGoogleZoom];
            self.mapView.camera = camera;
            self.myLocation = globalLocation;
            self.centLocation = globalLocation;
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [self checkAuthorizationStatus:status];
}

- (void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager {
//    manager.authorizationStatus
    if (@available(iOS 14.0, *)) {
        [self checkAuthorizationStatus:manager.authorizationStatus];
    } else {
        // Fallback on earlier versions
        [self checkAuthorizationStatus:manager.authorizationStatus];
    }
}

- (void)checkAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        if (self.mapView.isHidden) {
            self.mapView.hidden = NO;
            [self startUpdatingLocation];
        } else {
            [self startUpdatingLocation];
        }
        return;
    }
    
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        self.mapView.hidden = NO;
        // 定位权限被拒绝时，如果有全局位置则使用
        if (self.mapView.camera.zoom == 0 || (self.mapView.camera.target.latitude == 0 && self.mapView.camera.target.longitude == 0)) {
            CLLocationCoordinate2D globalLocation = [BRTools br_getGlobalLocation];
            if (globalLocation.latitude != 0 && globalLocation.longitude != 0) {
                GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:globalLocation.latitude
                                                                         longitude:globalLocation.longitude
                                                                              zoom:kGoogleZoom];
                [self.mapView animateToCameraPosition:camera];
                self.myLocation = globalLocation;
                self.centLocation = globalLocation;
            }
        }
    } else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

- (void)checkInitialPermissionStatus {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    // 如果有全局位置，先设置地图显示该位置
    dispatch_async(dispatch_get_main_queue(), ^{
        CLLocationCoordinate2D globalLocation = [BRTools br_getGlobalLocation];
        if (globalLocation.latitude != 0 && globalLocation.longitude != 0) {
            GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:globalLocation.latitude
                                                                     longitude:globalLocation.longitude
                                                                          zoom:kGoogleZoom];
            [self.mapView animateToCameraPosition:camera];
            self.myLocation = globalLocation;
            self.centLocation = globalLocation;
            // 显示当前位置标记
            [self showMyLocationMarker];
            // 显示附近网点中心标记视图
            [self showNearbySearchMarker];
        }
    });
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            [self.locationManager requestWhenInUseAuthorization];
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
            self.mapView.hidden = NO;
            [self startUpdatingLocation];
            break;
        case kCLAuthorizationStatusDenied:
        case kCLAuthorizationStatusRestricted:
            self.mapView.hidden = NO;
            // 定位权限被拒绝时，等待获取真实位置或使用全局位置
            break;
        default:
            self.mapView.hidden = NO;
            break;
    }
}

- (void)checkNetworkConnection {
    // 检查网络连接
    NSURL *url = [NSURL URLWithString:@"https://maps.googleapis.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 15.0; // 增加超时时间
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; // 忽略缓存
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"❌ 无法连接到Google Maps服务器: %@", error.localizedDescription);
                printf("❌ 无法连接到Google Maps服务器: %s\n", error.localizedDescription.UTF8String);
                
                // 如果网络连接失败，尝试使用备用方案
                [self tryAlternativeMapDisplay];
            } else {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                NSLog(@"✅ Google Maps服务器连接正常，状态码: %ld", (long)httpResponse.statusCode);
                printf("✅ Google Maps服务器连接正常，状态码: %ld\n", (long)httpResponse.statusCode);
            }
        });
    }];
    
    [task resume];
}

- (void)tryAlternativeMapDisplay {
    NSLog(@"🔄 尝试备用地图显示方案");
    printf("🔄 尝试备用地图显示方案\n");
    
    // 强制刷新地图
    if (self.mapView) {
        // 清除所有标记
        [self.mapView clear];
        
        // 使用全局位置或当前位置
        CLLocationCoordinate2D location = [BRTools br_getGlobalLocation];
        if (location.latitude == 0 && location.longitude == 0) {
            // 如果全局位置无效，使用当前位置
            location = self.myLocation;
        }
        
        // 如果位置有效，重新设置相机位置
        if (location.latitude != 0 && location.longitude != 0) {
            GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:location.latitude 
                                                                     longitude:location.longitude 
                                                                          zoom:kGoogleZoom];
            [self.mapView animateToCameraPosition:camera];
        }
        
        // 强制设置地图类型为普通模式
        self.mapView.mapType = kGMSTypeNormal;
        
        // 如果位置有效，添加一个明显的测试标记
        if (location.latitude != 0 && location.longitude != 0) {
            GMSMarker *testMarker = [[GMSMarker alloc] init];
            testMarker.position = location;
            testMarker.title = @"地图测试";
            testMarker.snippet = @"如果你能看到这个标记，说明地图工作正常";
            testMarker.map = self.mapView;
        }
        
        NSLog(@"✅ 备用地图显示方案已应用");
        printf("✅ 备用地图显示方案已应用\n");
    }
}

- (void)validateAPIKey {
    NSLog(@"🔑 验证API Key: %@", BRGMSMapKey);
    printf("🔑 验证API Key: %s\n", BRGMSMapKey.UTF8String);
    
    // 检查API Key格式
    if (BRGMSMapKey.length < 20) {
        NSLog(@"❌ API Key长度不足，可能无效");
        printf("❌ API Key长度不足，可能无效\n");
        return;
    }
    
    // 检查API Key是否包含有效字符
    NSCharacterSet *validChars = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"];
    NSCharacterSet *invalidChars = [validChars invertedSet];
    if ([BRGMSMapKey rangeOfCharacterFromSet:invalidChars].location != NSNotFound) {
        NSLog(@"❌ API Key包含无效字符");
        printf("❌ API Key包含无效字符\n");
        return;
    }
    
    NSLog(@"✅ API Key格式验证通过");
    printf("✅ API Key格式验证通过\n");
    
    // 检查Bundle ID
    NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];
    NSLog(@"📱 当前Bundle ID: %@", bundleId);
    printf("📱 当前Bundle ID: %s\n", bundleId.UTF8String);
    
    // 检查网络状态
    [self checkNetworkStatus];
}

- (void)checkNetworkStatus {
    // 检查网络连接状态
    NSURL *url = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/js"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 10.0;
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"❌ Google Maps API连接失败: %@", error.localizedDescription);
                printf("❌ Google Maps API连接失败: %s\n", error.localizedDescription.UTF8String);
            } else {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                NSLog(@"✅ Google Maps API连接成功，状态码: %ld", (long)httpResponse.statusCode);
                printf("✅ Google Maps API连接成功，状态码: %ld\n", (long)httpResponse.statusCode);
                
                // 如果连接成功但地图还是白屏，可能是API Key权限问题
                if (httpResponse.statusCode == 200) {
                    NSLog(@"⚠️ API连接正常但地图白屏，可能是API Key权限问题");
                    printf("⚠️ API连接正常但地图白屏，可能是API Key权限问题\n");
                }
            }
        });
    }];
    
    [task resume];
}

- (void)testMapTileLoading {
    NSLog(@"🧪 测试地图瓦片加载");
    printf("🧪 测试地图瓦片加载\n");
    
    // 测试直接访问Google Maps瓦片服务
    NSURL *tileURL = [NSURL URLWithString:@"https://mt1.google.com/vt/lyrs=m&x=0&y=0&z=1"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:tileURL];
    request.timeoutInterval = 10.0;
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"❌ 地图瓦片加载失败: %@", error.localizedDescription);
                printf("❌ 地图瓦片加载失败: %s\n", error.localizedDescription.UTF8String);
            } else {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                NSLog(@"✅ 地图瓦片加载成功，状态码: %ld, 数据大小: %ld bytes", (long)httpResponse.statusCode, (long)data.length);
                printf("✅ 地图瓦片加载成功，状态码: %ld, 数据大小: %ld bytes\n", (long)httpResponse.statusCode, (long)data.length);
            }
        });
    }];
    
    [task resume];
}

- (void)recreateMapView {
    if (self.mapView) {
        // 保存当前相机位置
        GMSCameraPosition *currentCamera = self.mapView.camera;
        
        // 移除旧的地图视图
        [self.mapView removeFromSuperview];
        self.mapView = nil;
        
        // 重新创建地图视图
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:currentCamera.target.latitude 
                                                                 longitude:currentCamera.target.longitude 
                                                                      zoom:currentCamera.zoom];
        self.mapView = [GMSMapView mapWithFrame:self.bounds camera:camera];
        self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.mapView.myLocationEnabled = YES;
        self.mapView.delegate = self;
        self.mapView.hidden = NO;
        self.mapView.mapType = kGMSTypeNormal;
        self.mapView.mapStyle = nil;
        
        // 重新添加到视图
        [self addSubview:self.mapView];
        
        // 不添加测试标记，等待真实定位
    }
}

- (void)testMapDisplay {
    // 测试地图显示 - 不添加硬编码位置，等待真实定位
    if (self.mapView) {
        // 清除所有标记
        [self.mapView clear];
        
        // 强制设置地图类型
        self.mapView.mapType = kGMSTypeNormal;
        
        // 不设置硬编码位置，让地图使用当前相机位置或等待定位
    }
}

- (void)forceRefreshMap {
    if (self.mapView) {
        // 强制刷新地图
        [self.mapView clear];
        
        // 重新设置地图类型
        self.mapView.mapType = kGMSTypeNormal;
        
        // 不设置硬编码位置，保持当前相机位置或等待定位
    }
}

/// mapView delegate
- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
    //即将移动地图 如果 gesture ==  Yes 则有手势触发
    self.gestrue = gesture;
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:willMove:)]) {
        [self.delegate br_mapView:mapView willMove:gesture];
    }
}

- (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(nonnull GMSCameraPosition *)position {
    //map移动之后调用
    
    // 移动后刷新位置
    self.centLocation = position.target;
    self.nearbySearchLocation = position.target;  // 更新附近网点位置为地图中心点
    
    // 同步更新全局位置管理器（地图中心位置）
    USERManager.globalLatitude = position.target.latitude;
    USERManager.globalLongitude = position.target.longitude;
    
    // 附近网点中心视图始终居中显示，不需要更新位置（因为它是悬浮在地图上层，永远居中）
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:idleAtCameraPosition:)]) {
        [self.delegate br_mapView:mapView idleAtCameraPosition:position];
    }
    
}

- (void)mapViewDidFinishTileRendering:(GMSMapView *)mapView {
    // 确保所有地图操作都在主线程执行
    dispatch_async(dispatch_get_main_queue(), ^{
        // 强制设置地图背景色和强制刷新
        mapView.backgroundColor = [UIColor clearColor];
        [mapView setNeedsDisplay];
        [mapView setNeedsLayout];
        [mapView layoutIfNeeded];
        
        // 地图加载完成后，如果当前位置无效且已有全局位置，则更新地图
        CLLocationCoordinate2D currentTarget = mapView.camera.target;
        if ((currentTarget.latitude == 0 && currentTarget.longitude == 0) || mapView.camera.zoom == 0) {
            CLLocationCoordinate2D globalLocation = [BRTools br_getGlobalLocation];
            if (globalLocation.latitude != 0 && globalLocation.longitude != 0) {
                GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:globalLocation.latitude
                                                                         longitude:globalLocation.longitude
                                                                              zoom:kGoogleZoom];
                [mapView animateToCameraPosition:camera];
                self.myLocation = globalLocation;
                self.centLocation = globalLocation;
            }
        }
    });
}

- (void)mapViewDidStartTileRendering:(GMSMapView *)mapView {
    // 地图开始渲染瓦片
}

- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
    // 点击地图空白位置
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:didTapAtCoordinate:)]) {
        [self.delegate br_mapView:mapView didTapAtCoordinate:coordinate];
    }
}

- (UIView *)mapView:(GMSMapView *)mapView markerInfoWindow:(GMSMarker *)marker {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:markerInfoWindow:)]) {
        return [self.delegate br_mapView:mapView markerInfoWindow:marker];
    }
    
    // 点击后展示MarkerView
    BRMarkerView *markerView = [[BRMarkerView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    
    return markerView;
}



- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
    //每次移动都调用
    // 更新附近网点位置为地图中心点
    self.nearbySearchLocation = position.target;
    // 附近网点中心视图始终居中显示，不需要更新位置（因为它是悬浮在地图上层，永远居中）
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:didChangeCameraPosition:)]) {
        [self.delegate br_mapView:mapView didChangeCameraPosition:position];
    }
}

- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:didTapMarker:)]) {
        return [self.delegate br_mapView:mapView didTapMarker:marker];
    }
    
    return YES;
}

- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    if (self.delegate && [self.delegate respondsToSelector:@selector(br_mapView:didTapInfoWindowOfMarker:)]) {
        [self.delegate br_mapView:mapView didTapInfoWindowOfMarker:marker];
    }
}

//#pragma mark - GMUClusterManager Delegate --
//- (BOOL)clusterManager:(GMUClusterManager *)clusterManager
//     didTapClusterItem:(id<GMUClusterItem>)clusterItem {
//
//    POIItem *item = (POIItem *)clusterItem;
//    item.isTap = item.isTap;
//
//    BRStationListModel *model = self.gmsMarkerArrs[item.index];
//    model.isTap = item.isTap;
//    UIImage *image;
//    if (model.isBusiness == 1) {
//        image = model.isTap ? UIImageMake(@"home_shopSel") : UIImageMake(@"home_shop") ;
//    }else {
//        image =  model.isTap ? UIImageMake(@"home_shopCloseSel")  : UIImageMake(@"home_shopClose") ;
//    }
//    item.icon = image;
//
//    return YES;
//}

#pragma mark - Set UI --
- (void)setUI {
    self.backgroundColor = kColorBGEC;
    [self addSubview:self.mapView];
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
//    [self addSubview:self.centImgView];
//    [self.centImgView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.offset(0);
////        make.centerY.offset(-12);
//        make.bottom.equalTo(self.mas_centerY).offset(0);
////        make.width.mas_equalTo(14);
////        make.height.mas_equalTo(24);
//    }];
    //重置google logo位置
    [self resetGoogleBtn];
    //配置网点
    [self setMapCluster];
    
    // 添加缩放按钮
    [self setupZoomButtons];
    
    // 检查权限状态
    [self checkInitialPermissionStatus];
    
    // 添加延迟检查，确保地图完全加载
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self checkMapStatus];
    });
    
    // 添加地图强制刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self forceRefreshMap];
    });
    
    // 确保地图显示有效位置
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 如果有全局位置或当前位置，更新地图
        CLLocationCoordinate2D globalLocation = [BRTools br_getGlobalLocation];
        if (globalLocation.latitude != 0 && globalLocation.longitude != 0) {
            GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:globalLocation.latitude
                                                                     longitude:globalLocation.longitude
                                                                          zoom:kGoogleZoom];
            [self.mapView animateToCameraPosition:camera];
            self.myLocation = globalLocation;
            self.centLocation = globalLocation;
        } else if (self.myLocation.latitude != 0 && self.myLocation.longitude != 0) {
            // 使用当前位置
            GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:self.myLocation.latitude
                                                                     longitude:self.myLocation.longitude
                                                                          zoom:kGoogleZoom];
            [self.mapView animateToCameraPosition:camera];
        }
        // 显示当前位置标记
        [self showMyLocationMarker];
        // 显示附近网点中心标记视图
        [self showNearbySearchMarker];
    });
    
    // 延迟显示当前位置标记和附近网点中心视图（确保地图完全加载）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showMyLocationMarker];
        [self showNearbySearchMarker];
    });
}

- (void)checkMapStatus {
    // 地图状态检查
}

- (void)changeShadowDrak {
    
    CGFloat view_h = kScale414(168 + kSafeAreaTopHeight);
    CGRect  fram = CGRectMake(0, 0, kScreenWidth, view_h);
    dispatch_async(dispatch_get_main_queue(), ^{
        CAGradientLayer *gl = [BRTools gradientLayerWithColors:[BRThemeManage br_homeMapShadowColors] rect:fram];
        [self->_shadowViw.layer addSublayer:gl];
    });
    
}


/// 设置集群
- (void)setMapCluster {
//    //设置集群manager
    id<GMUClusterAlgorithm> algorithm = [[GMUNonHierarchicalDistanceBasedAlgorithm alloc] init];
    //设置集群大小
    id<GMUClusterIconGenerator> iconGenerator = [[GMUDefaultClusterIconGenerator alloc] init];
    GMUDefaultClusterRenderer *renderer = [[GMUDefaultClusterRenderer alloc] initWithMapView:self.mapView clusterIconGenerator:iconGenerator];
//    renderer.animatesClusters = YES;//刷新时是否显示动画
    // 设置renderer的delegate，用于修复图标锚点问题
    renderer.delegate = self;
    _clusterManager = [[GMUClusterManager alloc] initWithMap:self.mapView algorithm:algorithm renderer:renderer];
//    [_clusterManager setDelegate:self mapDelegate:self];;
    
}

- (void)addMyLocationImage {
    UIImage *myLocationImage = [UIImage imageNamed: @"定位(1)"];
    UIImageView *myLocationImageView = [[UIImageView alloc] initWithImage: myLocationImage];
    [self addSubview: myLocationImageView];
    [myLocationImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self);
        make.size.mas_equalTo( CGSizeMake(40,40));
    }];
    myLocationImageView.hidden = YES;
}

- (void)resetGoogleBtn {
    //logo
    [self resetGoogleBtn:YES];
    
}

- (void)resetGoogleBtn:(BOOL)small {
    
    [self resetGoogleBtnY:50];
}

- (void)resetGoogleBtnY:(CGFloat)y {
    //logo 放大缩小后需要刷新位置
    UIButton *googleLogoButton;
    for (UIView *view in self.mapView.subviews[1].subviews) {
        for (UIView *subView in view.subviews) {
            if ([subView isKindOfClass:[UIButton class]]) {
                googleLogoButton = (UIButton *)subView;
            }
        }
    }
    googleLogoButton.enabled = NO;
//    CGFloat topY = small ? 0 : 0;
//    dispatch_async(dispatch_get_main_queue(), ^{
//        googleLogoButton.frame = CGRectMake(self.mj_w - googleLogoButton.frame.size.width, y, googleLogoButton.frame.size.width, googleLogoButton.frame.size.height);
//    });
    //60 22
    dispatch_async(dispatch_get_main_queue(), ^{
        googleLogoButton.frame = CGRectMake(0, self.mj_h - googleLogoButton.frame.size.height - kSafeAreaBottomHeight - 12, googleLogoButton.frame.size.width, googleLogoButton.frame.size.height);
    });
}

- (GMSMapView *)mapView {
    
    if (_mapView == nil) {
        // 创建地图视图 - 使用全局位置或等待真实定位
        CLLocationCoordinate2D initialLocation = [BRTools br_getGlobalLocation];
        // 如果全局位置无效，使用(0,0)等待定位
        if (initialLocation.latitude == 0 && initialLocation.longitude == 0) {
            initialLocation = CLLocationCoordinate2DMake(0, 0);
        }
        
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:initialLocation.latitude
                                                                 longitude:initialLocation.longitude
                                                                      zoom:kGoogleZoom];
        _mapView = [[GMSMapView alloc] initWithFrame:self.bounds camera:camera];
        
        // 基本设置
        _mapView.delegate = self;
        _mapView.myLocationEnabled = NO;  // 使用自定义定位逻辑
        
        // 立即开始定位，获取真实位置（定位成功后会自动更新）
        [self checkInitialPermissionStatus];
    }
    
    return _mapView;
}


- (CLLocationManager *)locationManager {
    
    if (_locationManager == nil) {
        
        _locationManager = [[CLLocationManager alloc] init];
        //设置代理
        _locationManager.delegate = self;
        //设置定位精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance = 10.0;//十米定位一次
        _locationManager.distanceFilter = distance;
        //如果没有授权则请求用户授权
        [_locationManager requestWhenInUseAuthorization];
    
    }
    return _locationManager;
}

- (void)setGmsMarkerArrs:(NSArray *)gmsMarkerArrs {
    _gmsMarkerArrs = gmsMarkerArrs;
//    [self setGMSMarkerShop:gmsMarkerArrs];
}

- (BRMapCenterLocView *)centImgView {
    
    if (_centImgView == nil) {
        _centImgView = [[BRMapCenterLocView alloc] init];
    }
    return _centImgView;
}

- (void)setIsDark:(BOOL)isDark {
    _isDark = isDark;
//    self.mapView setda
}

- (NSString *)mapStyle {
    return @"[{\"featureType\": \"all\",\"elementType\": \"labels.text.fill\",\"stylers\": [ {\"saturation\": 36},{ \"color\": \"#999999\"},{\"lightness\": 40}]},{\"featureType\": \"all\",\"elementType\": \"labels.text.stroke\",\"stylers\": [{\"visibility\": \"on\"},{\"color\": \"#ffffff\"},{\"lightness\": 16}]},{\"featureType\": \"all\",\"elementType\": \"labels.icon\",\"stylers\": [{\"visibility\": \"off\"}]},{\"featureType\": \"administrative\",\"elementType\": \"geometry.fill\",\"stylers\": [{\"color\": \"#ffffff\"},{\"lightness\": 20}]},{\"featureType\": \"administrative\",\"elementType\": \"geometry.stroke\",\"stylers\": [ {\"color\": \"#fefefe\"},{\"lightness\": 17}, {\"weight\": 1.2}]},{\"featureType\": \"landscape\",\"elementType\": \"geometry\",\"stylers\": [ {\"color\": \"#ffffff\"}, {\"lightness\": 20}] }, {\"featureType\": \"poi\",\"elementType\": \"geometry\",\"stylers\": [ {\"color\": \"#d2e6ff\"},{ \"lightness\": 21 }, {\"visibility\": \"off\" }] },{\"featureType\": \"poi.park\",\"elementType\": \"geometry\",\"stylers\": [{ \"color\": \"#daffe4\"},{\"lightness\": 21}, {\"visibility\": \"on\" }]},{\"featureType\": \"road.highway\",\"elementType\": \"geometry.fill\",\"stylers\": [ {\"color\": \"#f2f5fa\"}, {\"lightness\": 17 }]}, {\"featureType\": \"road.highway\",\"elementType\": \"geometry.stroke\", \"stylers\": [{\"color\": \"#ffffff\" }, {\"lightness\": 29 },{\"weight\": 0.2}]},{\"featureType\": \"road.arterial\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#f2f5fa\"}, {\"lightness\": 18}] },{\"featureType\": \"road.local\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#f2f5fa\"},{\"lightness\": 16}]},{\"featureType\": \"transit\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#f2f2f2\"},{\"lightness\": 19},{\"visibility\": \"on\" } ]},{\"featureType\": \"water\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#d2e6ff\"},{\"lightness\": 17},{\"visibility\": \"on\"}]},{\"featureType\": \"water\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#ffffff\"}]},{\"featureType\": \"water\",\"elementType\": \"labels.text.stroke\",\"stylers\": [ {\"color\": \"#d2e6ff\"}, {\"visibility\": \"off\"}]}]";
}

#pragma mark - Zoom Buttons --
- (void)setupZoomButtons {
    // 创建放大按钮
    self.zoomInButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.zoomInButton setTitle:@"+" forState:UIControlStateNormal];
    [self.zoomInButton setTitleColor:UIColor.qd_titleTextColor forState:UIControlStateNormal];
    self.zoomInButton.titleLabel.font = [UIFont boldSystemFontOfSize:24];
    self.zoomInButton.backgroundColor = UIColor.whiteColor;
    self.zoomInButton.layer.cornerRadius = 8;
    self.zoomInButton.layer.shadowColor = UIColor.blackColor.CGColor;
    self.zoomInButton.layer.shadowOffset = CGSizeMake(0, 2);
    self.zoomInButton.layer.shadowOpacity = 0.2;
    self.zoomInButton.layer.shadowRadius = 4;
    [self.zoomInButton addTarget:self action:@selector(zoomIn:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.zoomInButton];
    [self.zoomInButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(58);
        make.right.equalTo(self.mas_right).offset(-16);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    
    // 创建缩小按钮
    self.zoomOutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.zoomOutButton setTitle:@"−" forState:UIControlStateNormal];
    [self.zoomOutButton setTitleColor:UIColor.qd_titleTextColor forState:UIControlStateNormal];
    self.zoomOutButton.titleLabel.font = [UIFont boldSystemFontOfSize:24];
    self.zoomOutButton.backgroundColor = UIColor.whiteColor;
    self.zoomOutButton.layer.cornerRadius = 8;
    self.zoomOutButton.layer.shadowColor = UIColor.blackColor.CGColor;
    self.zoomOutButton.layer.shadowOffset = CGSizeMake(0, 2);
    self.zoomOutButton.layer.shadowOpacity = 0.2;
    self.zoomOutButton.layer.shadowRadius = 4;
    [self.zoomOutButton addTarget:self action:@selector(zoomOut:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.zoomOutButton];
    [self.zoomOutButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.zoomInButton.mas_bottom).offset(18);
        make.right.equalTo(self.mas_right).offset(-16);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
}

- (void)zoomIn:(UIButton *)sender {
    GMSCameraPosition *currentCamera = self.mapView.camera;
    float newZoom = currentCamera.zoom + 1.0;
    
    // 限制最大缩放级别为 20
    if (newZoom > 20) {
        newZoom = 20;
    }
    
    GMSCameraPosition *newCamera = [GMSCameraPosition cameraWithLatitude:currentCamera.target.latitude
                                                                longitude:currentCamera.target.longitude
                                                                     zoom:newZoom];
    [self.mapView animateToCameraPosition:newCamera];
}

- (void)zoomOut:(UIButton *)sender {
    GMSCameraPosition *currentCamera = self.mapView.camera;
    float newZoom = currentCamera.zoom - 1.0;
    
    // 限制最小缩放级别为 1
    if (newZoom < 1) {
        newZoom = 1;
    }
    
    GMSCameraPosition *newCamera = [GMSCameraPosition cameraWithLatitude:currentCamera.target.latitude
                                                                longitude:currentCamera.target.longitude
                                                                     zoom:newZoom];
    [self.mapView animateToCameraPosition:newCamera];
}

#pragma mark - GMUClusterRendererDelegate
/// 修复图标锚点问题，确保图标中心对齐到坐标位置
- (void)renderer:(id<GMUClusterRenderer>)renderer willRenderMarker:(GMSMarker *)marker {
    // 确保所有marker的groundAnchor都设置为(0.5, 0.5)，这样图标中心会正确对齐到坐标位置
    // 这可以修复图标偏移的问题
    if (marker.icon) {
        marker.groundAnchor = CGPointMake(0.5, 0.5);
    }
}

@end


@implementation BRMapCenterLocView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)topClick {
    if (self.topClickBlcok) self.topClickBlcok();
}


#pragma mark - UI --
- (void)setUI {
    
    self.backgroundColor = UIColor.clearColor;
    
    UIView *imgBGView = [[UIView alloc] init];
    imgBGView.backgroundColor = UIColor.clearColor;
    [self addSubview:imgBGView];
    
    [self addSubview:self.centerImg];
    [self.centerImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.offset(0);
        make.width.mas_equalTo(14);
        make.height.mas_equalTo(24);
    }];
    
    self.topImg.userInteractionEnabled = YES;
    [imgBGView addSubview:self.topImg];
    [self.topImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(4);
        make.centerX.offset(0);
        make.width.mas_equalTo(96);
        make.height.mas_equalTo(36);
    }];
    
    [self.topImg addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.offset(0);
        make.right.offset(-8);
    }];
    
    UIImageView *tImg = [[UIImageView alloc] initWithImage:UIImageMake(@"arrow_trangel_whitedown6")];
    [imgBGView addSubview:tImg];
    [tImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topImg.mas_bottom).offset(0);
        make.centerX.offset(0);
        make.width.mas_equalTo(6);
        make.height.mas_equalTo(4);
    }];
    _imgBgView = imgBGView;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topClick)];
    [self.topImg addGestureRecognizer:tap];
    
    [imgBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(4);
        make.right.offset(-4);
        make.bottom.equalTo(self.centerImg.mas_top).offset(0);
        make.width.mas_equalTo(104);
        make.height.mas_equalTo(48);
    }];
//    [imgBGView br_addBaseShadowDown];
    
    // Shadow Code
    imgBGView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.16].CGColor;
    imgBGView.layer.shadowOffset = CGSizeMake(0,0);
    imgBGView.layer.shadowRadius = 16;
    imgBGView.layer.shadowOpacity = 1;
}

- (UIImageView *)centerImg {
    
    if (_centerImg == nil) {
        _centerImg = [[UIImageView alloc] initWithImage:UIImageMake(@"map_center")];
    }
    return _centerImg;
}
- (UIImageView *)topImg {
    
    if (_topImg == nil) {
        _topImg = [[UIImageView alloc] initWithImage:UIImageMake(@"home_nearby")];
    }
    return _topImg;
}

- (QMUILabel *)titleL {
    
    if (_titleL == nil) {
        _titleL = [BRToolsView br_label:Localized(@"home_nearbyMaerchants") textColor:kColorTitle font:[UIFont fontM:12] textAlignment:NSTextAlignmentCenter];
        _titleL.numberOfLines = 2;
    }
    return _titleL;
}

@end
